/*
 * @Author: 260156 260156@gree.com.cn
 * @Date: 2022-08-05 14:53:04
 * @LastEditors: 260156 260156@gree.com.cn
 * @LastEditTime: 2022-09-08 10:06:42
 * @FilePath: \gree-zst-web\src\composition\addEditDialog.ts
 * @Description: 新增和编辑弹框 可复用内容
 *
 * Copyright (c) 2022 by 260156 260156@gree.com.cn, All Rights Reserved.
 */
import type { Ref } from "vue";
import { cloneDeep } from "lodash";
import type { FormInstance, FormRules } from "element-plus";

export const useAddEditDialog = <EditForm, EditFormRules>({
  initForm,
  formRules,
  props,
  emits,
}: {
  initForm: EditForm;
  formRules: EditFormRules;
  emits: (arg1: any, arg2?: any) => void;
  props: {
    flag?: "edit" | "add";
    formData?: EditForm;
  };
}) => {
  const form = ref<EditForm>(cloneDeep(initForm)) as Ref<EditForm>;

  const title = computed(() => (props.flag === "edit" ? "编辑" : "新增"));
  const isDisabled = computed<boolean>(() => props.flag === "edit");

  const formRef = ref<FormInstance>();
  // form验证
  const rules = reactive<FormRules>(formRules as FormRules);

  // 弹框打开和关闭
  const handleOpen = () => {
    props.flag === "edit" &&
      (form.value = cloneDeep(props.formData) as EditForm); // 更新表单数据
    formRef.value && formRef.value.clearValidate();
  };
  const handleClose = () => {
    form.value = cloneDeep(initForm);
    // 点击X关闭弹框时，需要更新visible
    emits("update:modelValue", false);
  };

  // 点击取消和确认按钮
  const handleCancel = () => {
    emits("handleClose");
    // 点击取消按钮时，需要更新visible
    emits("update:modelValue", false);
  };
  const handleConfirm = (formEl: any) => {
    formEl.validate((valid: boolean) => {
      if (valid) {
        emits("handleConfirm", form.value);
        // 点击确认按钮时，需要在父组件api调用成功后更新visible，此处不做更新
      }
    });
  };

  return {
    form,
    title,
    isDisabled,
    formRef,
    rules,
    handleClose,
    handleOpen,
    handleCancel,
    handleConfirm,
  };
};
